package com.eightbears.beboy.ui.user.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.FaceGVAdapter;
import com.eightbears.beboy.adapter.FacePageAdeapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.Callback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.ClassDialog;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.base.view.gif.AnimatedGifDrawable;
import com.eightbears.beboy.base.view.gif.AnimatedImageSpan;
import com.eightbears.beboy.base.view.image.adapter.ImagePickerAdapter;
import com.eightbears.beboy.base.view.image.ui.ImageGridActivity;
import com.eightbears.beboy.base.view.image.ui.ImageViewDelActivity;
import com.eightbears.beboy.base.view.image.view.ImageItem;
import com.eightbears.beboy.base.view.image.view.ImagePicker;
import com.eightbears.beboy.base.view.picker.DatePicker;
import com.eightbears.beboy.base.view.viperpager.CirclePageIndicator;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SENDPOST;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_ADDRESS;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_CITY;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_DISTRICT;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LATITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LONGITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_PROVINCE;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.EVENT_PUBLISH_POST_SUCCESS;

/**
 * 发帖页面
 */
public class PublishContentsActivity extends BaseActivity
        implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    public static final int REQUEST_CODE_LOCATION = 1;

    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;
    @BindView(R.id.btn_send)
    Button btn_send;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_publish_price)
    EditText et_publish_price;
    @BindView(R.id.et_content)
    EditText et_content;
    @BindView(R.id.et_publish_shopname)
    EditText et_publish_shopname;
    @BindView(R.id.tv_publish_time)
    TextView tv_publish_time;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_publish_mobile)
    EditText et_publish_mobile;
    @BindView(R.id.tv_publish_showlocation)
    TextView tv_publish_showlocation;
    @BindView(R.id.et_publish_themeprice)
    EditText et_publish_themeprice;
    @BindView(R.id.rl_publish_shoulocation)
    RelativeLayout rl_publish_shoulocation;
    @BindView(R.id.iv_publish_right)
    ImageView iv_publish_right;
    @BindView(R.id.tv_classes_name)
    TextView tv_classes_name;
    @BindView(R.id.iv_classes)
    ImageView iv_classes;
    @BindView(R.id.activity_publish_content)
    SwipeBackLayout activity_publish_content;
    @BindView(R.id.view_face)
    View view_face;
    @BindView(R.id.vp_live_room_face)
    ViewPager vp_live_room_face;                      // 表情容器
    @BindView(R.id.cpi_live_room_indicator)
    CirclePageIndicator cpi_live_room_indicator;      // 表情分页
    @BindView(R.id.slv_view)
    ScrollView slv_view;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList;                  //当前选择的所有图片
    private int maxImgCount = 9;                                //允许选择图片最大数
    private String mLatitude = "";
    private String mLongitude = "";
    private String classesId = "";

    private boolean isPublish = false;
    private PostFormBuilder builderPost = OkHttpUtils.post();
    private ClassDialog mClassDialog;


    private JSONArray faceJson;
    private List<String> faceName;                           // 表情名称
    private List<String> facePath;                           // 表情路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_contents);
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        LocationEntity locationEntity = SPUtil.getUserLocation();
        tv_title.setText(R.string.text_title_publish_post);
        //侧滑删除实力化
    }

    @Override
    protected void initData() {
        selImageList = new ArrayList<>();
        tv_loading_text.setText(getText(R.string.text_post_posting));
        faceJson = CommonUtils.getFromAssets2Json("face/face.json", this);  // 取得表情
        faceName = new ArrayList<>();               // 表情名称
        facePath = new ArrayList<>();               //
        initFaceLayout();
        initAdapter();
    }

    @Override
    protected void initEvent() {
        activity_publish_content.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        et_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view_face.setVisibility(View.GONE);
            }
        });
        slv_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view_face.setVisibility(View.GONE);
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.rl_publish_shoulocation)
    void location() {
        startActivityForResult(new Intent(mContext, SelLocationActivity.class), REQUEST_CODE_LOCATION);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @OnClick(R.id.rl_publish_time)
    void time() {
        setTime();
    }

    @OnClick(R.id.tv_publish_time)
    void tv_time() {
        setTime();
    }

    @OnClick(R.id.btn_send)
    void sendContent() {
        sendBuilder();
    }

    @OnClick(R.id.rl_classes)
    void classes() {
        mClassDialog = new ClassDialog(mContext, R.style.MyDialog);
        mClassDialog.setOnItemClickListener(new ClassDialog.onDialogItemClickListener() {
            @Override
            public void onItemClick(String s, String id) {
                iv_classes.setVisibility(View.GONE);
                tv_classes_name.setVisibility(View.VISIBLE);
                tv_classes_name.setText(s);
                classesId = id;
                mClassDialog.dismiss();
            }
        });
        mClassDialog.show();
        mClassDialog.setCancelable(true);//默认是true
        mClassDialog.setCanceledOnTouchOutside(true);//默认是true
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImageViewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
        }
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    /**
     * 构建内容
     */
    private void sendBuilder() {
        String content = et_content.getText().toString().trim();    // 帖子内容
        if (TextUtils.isEmpty(content)) {
            ShowToast.showLongToast(R.string.alert_input_empty);
            return;
        }

        // 必填项
        builderPost.url(URL_SENDPOST);
        builderPost.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builderPost.addParams("city_id", SPUtil.getUserLocation().getCityId());
        builderPost.addParams("province_id", SPUtil.getUserLocation().getProvinceId());
        builderPost.addParams("district_id", SPUtil.getUserLocation().getDistrictId());
        builderPost.addParams("post", content);
        String themePrice = et_publish_themeprice.getText().toString();
        themePrice = themePrice.equals("") ? "0" : themePrice;
        String time = tv_publish_time.getText().toString();
        String shopName = et_publish_shopname.getText().toString();
        String classes = tv_classes_name.getText().toString();
        final String phone = et_publish_mobile.getText().toString();
        String location = tv_publish_showlocation.getText().toString();
        String price = et_publish_price.getText().toString();
        price = price.equals("") ? "0" : price;

        if (Double.parseDouble(themePrice) > 0) {
            if (TextUtils.isEmpty(time)) {
                ShowToast.showLongToast(R.string.text_post_error_time);
                return;
            }

            if (TextUtils.isEmpty(shopName)) {
                ShowToast.showLongToast(R.string.text_post_error_shop_name);
                return;
            }

            if (TextUtils.isEmpty(classes)) {
                ShowToast.showLongToast(R.string.text_post_error_shop_classes);
                return;
            }

            if (TextUtils.isEmpty(phone)) {
                ShowToast.showLongToast(R.string.text_post_error_phone);
                return;
            }

            if (TextUtils.isEmpty(location)) {
                ShowToast.showLongToast(R.string.text_post_error_location);
                return;
            }

            if (TextUtils.isEmpty(themePrice)) {
                ShowToast.showLongToast(R.string.text_post_error_theme_price);
                return;
            }
        }

        builderPost.addParams("consumed_at", time);
        builderPost.addParams("shop", shopName);
        builderPost.addParams("longitude", mLongitude);
        builderPost.addParams("latitude", mLatitude);
        builderPost.addParams("address", location);
        builderPost.addParams("category", classesId);
        builderPost.addParams("contact", phone);
        builderPost.addParams("consumption", price);
        builderPost.addParams("price", themePrice);

        changeViewSend();//改变view的状态

        for (int i = 0; i < selImageList.size(); i++) {
            builderPost.addFile("images[]", "images", new File(selImageList.get(i).path));
        }
        isPublish = true;
        builderPost.build().execute(new Callback() {
            @Override
            public void onResponse(Object response) {
                ShowToast.showLongToast(R.string.text_post_success);
                EventBus.getDefault().post(EVENT_PUBLISH_POST_SUCCESS);//发消息通知已经发布成功
                finish();
            }

            @Override
            public Object parseNetworkResponse(Response response) throws Exception {
                return null;
            }

            @Override
            public void inProgress(float progress) {//发布的过程中进度监听
                super.inProgress(progress);
                btn_send.setText("正在发布中..." + ((int) (progress * 100)) + "%");
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                cancelSend();
                view_loading.setVisibility(View.GONE);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(PublishContentsActivity.this, status_error);
            }
        });
    }

    /**
     * 设置时间
     */
    private void setTime() {
        int[] date = CommonUtils.getDate();
        final DatePicker picker = new DatePicker(this);
        picker.setUseWeight(true);
        picker.setCanceledOnTouchOutside(true);
        picker.setRangeStart(1900, 1, 1);
        picker.setRangeEnd(2111, 1, 1);
        picker.setSelectedItem(date[0], date[1] , date[2]);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                String publish_time = year + "-" + month + "-" + day;
                tv_publish_time.setText(publish_time);
            }
        });
        picker.show();
    }

    /**
     * 发送，更改界面
     */
    private void changeViewSend() {
        view_loading.setVisibility(View.VISIBLE);//显示滚动圈
        btn_send.setClickable(false);//禁止点击
        btn_send.setEnabled(false);//不能点击
        ll_back.setEnabled(false);//不能点击
        btn_send.setBackgroundResource(R.drawable.bg_gray_style);//按钮变灰
        btn_send.setText(R.string.text_post_posting);
        ll_back.setClickable(false);//禁止回退
    }

    /**
     * 发送取消
     */
    private void cancelSend() {
        view_loading.setVisibility(View.GONE);//显示滚动圈
        btn_send.setClickable(true);//禁止点击
        btn_send.setEnabled(true);//不能点击
        ll_back.setEnabled(true);//不能点击
        btn_send.setBackgroundResource(R.drawable.background_circle_bead_blue_style);//按钮变灰
        btn_send.setText(R.string.text_publish);
        ll_back.setClickable(true);//禁止回退
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                selImageList.clear();
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        } else if (requestCode == REQUEST_CODE_LOCATION) {
            if (null == data) {
                ShowToast.showLongToast(getString(R.string.text_canceled));
                return;
            }

            mLatitude = String.valueOf(data.getExtras().getDouble(PARAMS_LATITUDE));
            mLongitude = String.valueOf(data.getExtras().getDouble(PARAMS_LONGITUDE));
            String address = data.getExtras().getString(PARAMS_ADDRESS);
            String provinceId = data.getExtras().getString(PARAMS_PROVINCE);
            String districtId = data.getExtras().getString(PARAMS_DISTRICT);
            String cityId = data.getExtras().getString(PARAMS_CITY);
            tv_publish_showlocation.setText(address);
            iv_publish_right.setVisibility(View.GONE);
        }
    }


    /**
     * 表情布局初始化
     */
    private void initFaceLayout() {
        for (int i = 0; i < faceJson.length(); i++) {
            try {
                JSONArray face = (JSONArray) faceJson.get(i);
                facePath.add((String) face.get(0));
                faceName.add((String) face.get(1));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        List<View> lv = new ArrayList<>();
        lv.add(viewPagerItem());
        FacePageAdeapter adapter = new FacePageAdeapter(lv);
        vp_live_room_face.setAdapter(adapter);
        vp_live_room_face.setCurrentItem(0);
        cpi_live_room_indicator.setViewPager(vp_live_room_face);
    }

    private View viewPagerItem() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.face_gridview, null);
        GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);
        FaceGVAdapter mGvAdapter = new FaceGVAdapter(facePath, faceName, this);
        gridview.setAdapter(mGvAdapter);
        gridview.setNumColumns(7);
        // 单击表情执行的操作
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    String png = ((TextView) ((LinearLayout) view).getChildAt(1)).getText().toString();
                    String facePath = ((TextView) ((LinearLayout) view).getChildAt(2)).getText().toString();
                    insert(getFace(facePath, png));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return gridview;
    }

    /**
     * 向输入框里添加表情
     */
    private void insert(CharSequence text) {
        int iCursorStart = Selection.getSelectionStart((et_content.getText()));
        int iCursorEnd = Selection.getSelectionEnd((et_content.getText()));
        if (text.length() + iCursorStart > 200) {
            return;
        }
        if (iCursorStart != iCursorEnd) {
            (et_content.getText()).replace(iCursorStart, iCursorEnd, "");
        }
        int iCursor = Selection.getSelectionEnd((et_content.getText()));
        (et_content.getText()).insert(iCursor, text);
    }

    private SpannableStringBuilder getFace(String facePath, String faceName) {
        SpannableStringBuilder sb = new SpannableStringBuilder();
        try {
            String filePath = "face/" + facePath;
            String tempText = faceName;
            sb.append(tempText);
            sb.setSpan(new ImageSpan(this, BitmapFactory.decodeStream(getAssets().open(filePath))),
                    sb.length() - tempText.length(), sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb;
    }

    private boolean checkGifExist(String message) {
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007F\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(message);
        if (m.find()) {
            return true;
        } else {
            return false;
        }
    }


    // 对文字处理后显示
    private SpannableStringBuilder handler(final TextView gifTextView, String content) {

        if (faceJson == null) {
            faceJson = CommonUtils.getFromAssets2Json("face/face.json", mContext);
        }
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007f\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            for (int i = 0; i < faceJson.length(); i++) {
                try {
                    JSONArray arr = (JSONArray) faceJson.get(i);
                    String faceTemp = arr.get(1).toString();
                    if (faceTemp.equals(m.group())) {
                        String gif = "face/" + arr.get(0);
                        InputStream is = mContext.getAssets().open(gif);
                        sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        is.close();
                    }
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb;
    }

    @OnClick(R.id.iv_biaoqing)
    void showFace() {
        if (view_face.getVisibility() == View.VISIBLE) {
            view_face.setVisibility(View.GONE);
            InputMethodUtils.showInputMethod(et_content, 0);
        } else {
            InputMethodUtils.closeInputMethod(this, et_content);
            view_face.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && selImageList.size() > 0 && isPublish) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        DefaultDialog.Builder defaultDialog = new DefaultDialog.Builder(this);
        defaultDialog.setTitle(R.string.prompt);
        defaultDialog.setMessage(getString(R.string.text_image_uploading_close));
        defaultDialog.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                dialog.dismiss();
            }
        });
        defaultDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        defaultDialog.create().show();
    }
}
